import json

import commonTool.properties_tool as read
import manager.tool.ReplaceVarData as replaceVar
from commonTool.logs.logs_wrapper import LogUtil
from manager.config import Base_File_Config as fileConfig

logs = LogUtil()


class ApiTool:
    """
    接口工具类，构建日志工具，环境变量工具，参数替换工具
    """

    @staticmethod
    @logs
    def buildInitLog(content, url):
        """
        初始化接口统一日志打印
        :param content: 接口名
        :param url: url
        :return: void
        """
        # print('正在初始化{}接口 url:{}'.format(content, url))
        logs.info(f'正在初始化{content}接口 url:{url}')

    @staticmethod
    @logs
    def buildRequestLog(api_name, data):
        """
        请求参数统一日志打印
        :param api_name: 接口名
        :param data: 请求参数
        :return: void
        """
        request_data = f'请求体 --> {data}'
        if data is None or data == '' or len(data) <= 0:
            request_data = '请求体 --> 无参调用'

        logs.info(f'{request_data}')
        logs.info(f'正在调用 {api_name} 接口 ...')

    @staticmethod
    def buildEnvironmentVariable():
        """
        配置测试运行环境变量文件写入读取对象
        默认 Path = ${项目目录}/data/environmentVariable/${{环境}}.properties
        :return: 操作 Properties 对象
        """
        environment_variable_path = fileConfig.ENVIRONMENT_PROPERTIES_PATH  # 要操作的properties文件的路径
        return read.PropertiesTool(environment_variable_path, 'utf-8')  # 操作 properties 对象

    @staticmethod
    def buildReplaceParam(param):
        """
        构建参数替换，指定替换格式：{{var}}
        e.g. {{key}} ==> value

        :param param: 需替换的数据
        :return: 替换后数据
        """
        return replaceVar.replaceVarData(param)

    @staticmethod
    def buildReplaceList(paramList):
        """
        构建参数替换，指定替换格式：{{var}}
        e.g. {{key}} ==> value

        :param paramList: 需替换的数据
        :return: 替换后数据
        """
        return replaceVar.replaceListVarData(paramList)

    @staticmethod
    def buildFormParam(key, value):
        """
        构建请求参数 form 表单格式模板
        e.g. ['username','password']['haha','123456'] ==> username=haha&password=123456

        :param key:  入参替换Key
        :param value:  入参参数value
        :return: form 模板
        """
        param = ''
        if isinstance(key, str):
            return key + '=' + str(value)
        for i in range(0, len(key)):
            param += key[i] + '=' + str(value[i]) + '&'
        return param[0: len(param) - 1]

    @staticmethod
    def buildJsonParam(key, value):
        """
        构建请求参数JSON格式模板
        e.g. ['key'], ['value'] ==> {"key": "value"}

        :param key:  入参替换Key
        :param value:  入参参数value
        :return: form 模板
        """
        d = {}
        for i in range(0, len(key)):
            d[key[i]] = value[i]
        return json.dumps(d)
